package com.czxy.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.joda.time.DateTime;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;

/**
 * @ClassName: JwtHelper
 * @Description: token工具类
 * @author: yuanxinqi
 * @version: V 2.0.0
 * @since: (jdk_1.8)
 */ 
public class JWTUtil {


    /**
     * 获取token中的参数
     *
     * @param token
     * @return
     */
    public static Claims parseToken(String token, String key) {
        if ("".equals(token)) {
            return null;
        }

        try {
            return Jwts.parser()
                    .setSigningKey(DatatypeConverter.parseBase64Binary(key))
                    .parseClaimsJws(token).getBody();
        } catch (Exception ex) {
            return null;
        }
    }

    /**
     * 生成token
     * @param tname   token中需要存放的信息
     * stuname  token中需要存放的信息
     * sex      token中需要存放的信息
     * @param key      秘钥，盐，撒的盐不一样，出来的密码不一样
     * @param expireMinutes token的存活时间
     * @return
     */
    public static String createToken(Integer tid,String tname, String key, int expireMinutes) {
        //定义加密算法
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        //生成签名密钥
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(key);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

        //添加构成JWT的参数
        JwtBuilder builder = Jwts.builder()
//                .setHeaderParam("type", "JWT")
//                .setSubject(userId.toString())
                .claim("tid", tid) // 设置载荷信息
                .claim("tname", tname) // 设置载荷信息
                .setExpiration(DateTime.now().plusMinutes(expireMinutes).toDate())// 设置超时时间
                .signWith(signatureAlgorithm, signingKey);//设置签名

        //生成JWT
        return builder.compact();
    }


    public static void main(String[] args) {
//        String token1 = JWTUtil.createToken(1001, "lucy", "admin", 30);
//        System.out.println(token1);
//
//
//        String token2 = JWTUtil.createToken(1001, "lucy", "admin", 30);
//        System.out.println(token2);


        String token1 = "eyJhbGciOiJIUzI1NiJ9.eyJ0aWQiOjEwMDEsInRuYW1lIjoibHVjeSIsImV4cCI6MTY2NTcxMTQ5N30.XXtQEoOnVULxHVnpx0AMVBK2B4V-Vi9jXo7CUgsGgbI";
        String token2 = "eyJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOjEwMDEsInN0dW5hbWUiOiJsdWN5IiwiZXhwIjoxNjY1NDUwNzI5fQ.o2okhKnG4YQeAA-G_94aCZH2z30w70N7WR89n2-eF4I";
//
//
        Claims claims = JWTUtil.parseToken(token1, "admin");
        System.out.println(claims);

    }


}
